package com.ziyucoding.minispring.context;

import com.ziyucoding.minispring.beans.BeansException;
import com.ziyucoding.minispring.beans.factory.BeanFactory;
import com.ziyucoding.minispring.beans.factory.support.SimpleBeanFactory;
import com.ziyucoding.minispring.beans.factory.config.BeanDefinition;
import com.ziyucoding.minispring.beans.factory.xml.XmlBeanDefinitionReader;
import com.ziyucoding.minispring.core.ClassPathXmlResource;
import com.ziyucoding.minispring.core.Resource;

/**
 * 应用上下文
 *
 * @author ziyucoding
 * @date 2023-05-08
 **/
public class ClassPathXmlApplicationContext implements BeanFactory {

    BeanFactory beanFactory;

    /**
     * context负责整合容器的启动过程，读外部配置，解析Bean定义，创建BeanFactory
     *
     * @param fileName
     * @return null
     */
    public ClassPathXmlApplicationContext(String fileName) {
        Resource resource = new ClassPathXmlResource(fileName);
        BeanFactory beanFactory = new SimpleBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        reader.loadBeanDefinitions(resource);
        this.beanFactory = beanFactory;
    }

    /**
     * context再对外提供一个getBean，底下就是调用的BeanFactory对应的方法
     *
     * @param beanName
     * @return Object
     */
    @Override
    public Object getBean(String beanName) throws BeansException {
        return this.beanFactory.getBean(beanName);
    }

    @Override
    public void registerBeanDefinition(BeanDefinition beanDefinition) {
        this.beanFactory.registerBeanDefinition(beanDefinition);
    }
}
